#include "device/DeviceBase.h"
#include "core/Logger.h"

#include <chrono>

namespace ems {
namespace device {

DeviceBase::DeviceBase(const std::string& id, const std::string& name, const std::string& type)
    : id_(id), name_(name), type_(type), status_(DeviceStatus::DISCONNECTED),
      enabled_(true), pollInterval_(5000), lastCollectionTime_(0), lastErrorTime_(0) {
}

DeviceBase::~DeviceBase() {
    // 不在析构函数中调用纯虚函数
}

std::string DeviceBase::getStatusString() const {
    switch (status_.load()) {
        case DeviceStatus::DISCONNECTED: return "DISCONNECTED";
        case DeviceStatus::CONNECTING: return "CONNECTING";
        case DeviceStatus::CONNECTED: return "CONNECTED";
        case DeviceStatus::ERROR: return "ERROR";
        case DeviceStatus::MAINTENANCE: return "MAINTENANCE";
        default: return "UNKNOWN";
    }
}

std::string DeviceBase::getLastError() const {
    std::lock_guard<std::mutex> lock(errorMutex_);
    return lastError_;
}

void DeviceBase::setStatus(DeviceStatus status) {
    DeviceStatus oldStatus = status_.exchange(status);
    if (oldStatus != status) {
        LOG_INFO("Device " << id_ << " status changed: " << getStatusString());
    }
}

void DeviceBase::setLastError(const std::string& error) {
    {
        std::lock_guard<std::mutex> lock(errorMutex_);
        lastError_ = error;
    }
    
    lastErrorTime_ = getCurrentTimestamp();
    
    if (status_ != DeviceStatus::ERROR) {
        setStatus(DeviceStatus::ERROR);
    }
    
    LOG_ERROR("Device " << id_ << " error: " << error);
}

uint64_t DeviceBase::getCurrentTimestamp() const {
    auto now = std::chrono::system_clock::now();
    auto timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
    return static_cast<uint64_t>(timestamp.count());
}

}  // namespace device
}  // namespace ems